package com.zy.portal.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.zy.common.util.CookieUtils;
import com.zy.pojo.TbUser;
import com.zy.portal.service.impl.UserServiceImpl;

/**
 * 登录访问拦截器
 * @author fys
 *
 */
public class LoginInterceptor implements HandlerInterceptor {

	@Autowired
	private UserServiceImpl service;

	/*
	 * 访问页面之前，springmvc拦截/item/**，判断是否登陆
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception { // 判断用户是否登录
		// 从cookie中取token,如果已登录则有值
		String cookieValue = CookieUtils.getCookieValue(request, "TT_TOKEN");
		// 根据token取用户信息，调用sso系统接口
		TbUser user = service.getUserByToken(cookieValue);

		if (user == null) {
			// 重定向或者远程调用  http://localhost:8084/page/login?redirect=xxxx  tao_sso 重新登陆
			response.sendRedirect(
					service.SSO_BASE_URL + service.SSO_PAGE_LOGIN + "?redirect=" + request.getRequestURL());
			//拦截，不予访问
			return false;
		}
		// 放行，可以访问
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception { // TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception { // TODO Auto-generated method stub

	}

}
